from api.login import LoginAPI
import requests
import pytest
import json
import config


# 测试数据
# test_data = {
#     ("admin", "HM_2023_test", 200, "成功", 200),
#     ("", "HM_2023_test", 200, "错误", 500),
#     ("jack666", "HM_2023_test", 200, "错误", 500)
# }

# 读取json文件
def build_data(json_file):
    # 定义空列表
    test_data = []
    # 打开json文件
    with open(json_file, "r", encoding='utf-8') as f:
        # 加载json测试数据
        json_data = json.load(f)
        # 循环遍历测试数据
        for case_data in json_data:
            print("----------------开始打印------------------")
            print(case_data)
            print(type(case_data))
            # 转换数据格式[{},{}] ==> [(),()]
            username = case_data.get("username")
            password = case_data.get("password")
            status = case_data.get("status")
            msg = case_data.get("msg")
            code = case_data.get("code")
            test_data.append((username, password, status, msg, code))
        return test_data


# 创建测试类
class TestLoginAPI:
    uuid = None

    # 前置条件
    def setup_method(self):
        # 实例化接口类
        self.login_api = LoginAPI()
        response = self.login_api.get_verify_code()
        print(response.json())
        # 提取验证码接口返回的uuid参数值
        TestLoginAPI.uuid = response.json().get("uuid")

    # 后置条件
    def teardown_method(self):
        pass

    @pytest.mark.parametrize("username,password,status,msg,code",
                             build_data(json_file=config.BASE_PATH + "/data/login.json"))
    # 登录成功
    def test01_success(self, username, password, status, msg, code):
        login_data = {
            "username": username,
            "password": password,
            "code": "2",
            "uuid": TestLoginAPI.uuid
        }
        response = self.login_api.login(test_data=login_data)
        # 断言响应状态码为200
        assert status == response.status_code
        # 断言响应数据包含“成功”
        assert msg in response.text
        # 断言响应json数据中包含数据值
        assert code == response.json().get("code")
